<template>
  <page-layout>
    <a-card>
      <a-steps v-model:current="current" :current="current" @change="handleStep">
        <a-step v-for="step in steps" :key="step.title" :title="step.title"/>
      </a-steps>
      <div class="mt-20">
        <baseInfoForm ref="baseInfoFormRef" v-if="Number(current) === 0"/>
        <transferInfoForm ref="transferInfoFormRef" v-if="Number(current) === 1"/>
        <otherInfoForm ref="otherInfoRef" v-if="Number(current) === 2"/>
        <fourInfoForm ref="fourInfoRef" v-if="Number(current) === 3"/>
      </div>
      <div class="box-ver-hor-center">
        <a-button type="primary" @click="saveForm" class="mr-20">{{ t('button.save') }}</a-button>
        <a-button type="primary" @click="nextStep" v-if="current !== steps.length - 1">{{ t('button.next') }}</a-button>
      </div>
    </a-card>
  </page-layout>
</template>

<script>
import baseInfoForm from './components/base-info-form'
import transferInfoForm from './components/transfer-info-form'
import otherInfoForm from './components/other-info-form'
import fourInfoForm from './components/four-info-form'
import { isEmpty } from '@/tools/common'
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { save, update, selectById } from '@/api/module/school'
import { message } from 'ant-design-vue'
import mixin from '@/mixins'

export default {
  name: 'college-manage-add',
  components: {
    baseInfoForm,
    transferInfoForm,
    otherInfoForm,
    fourInfoForm
  },
  setup() {
    const { returnRoute } = mixin.setup()
    const baseInfoFormRef = ref(null)
    const transferInfoFormRef = ref(null)
    const otherInfoRef = ref(null)
    const fourInfoRef = ref(null)
    const current = ref(0)
    const state = reactive({
      current: 0,
      data: {
        contactsList: [],
        schCalendarYearList: [],
        schMailboxSuffix: '',
        files: [],
        logo: [],
        contract: [],
        other: [],
        courseHeader: [],
        courseFooter: [],
      }
    })
    const router = useRouter()
    const route = useRoute()
    const { t } = useI18n()
    const steps = [
      { title: '填写基础信息', content: 'First-content' },
      { title: '填写转学分信息', content: 'Second-content' },
      { title: '填写其他信息', content: 'Last-content' },
      { title: '学校联系人', content: 'Four-content' }
    ]

    const submitData = reactive({})

    const editData = reactive({
      data: {}
    })
    const handleStep = async (e) => {
      const isEdit = !isEmpty(route.query.id)
      if (state.current == 0) {
        const { modelForm, errorFields } = await baseInfoFormRef.value.submit()
        if (errorFields) {
          current.value = state.current
          nextTick(() => {
            baseInfoFormRef.value.updateFormData(modelForm)
            message.warning('请先完善必填数据')
          })
          return
        }
        submitData.baseInfo = modelForm
        state.data = { ...state.data, ...modelForm}
      }
      if (state.current == 1) {
        const { modelForm, errorFields } = await transferInfoFormRef.value.submit()
        if (errorFields) {
          current.value = state.current
          nextTick(() => {
            transferInfoFormRef.value.updateFormData(modelForm)
            message.warning('请先完善必填数据')
          })
          return
        }
        submitData.transferInfo = modelForm
        state.data = { ...state.data, ...modelForm}
      }
      if (state.current == 2) {
        const { modelForm, errorFields } = await otherInfoRef.value.submit()
        if (errorFields) {
          current.value = state.current
          nextTick(() => {
            otherInfoRef.value.updateFormData(modelForm)
            message.warning('请先完善必填数据')
          })
          return
        }
        submitData.otherInfo = modelForm
        state.data = { ...state.data, ...modelForm}
      }
      if (state.current == 3) {
        const { modelForm, errorFields } = await fourInfoRef.value.submit()
        if (errorFields) {
          current.value = state.current
          nextTick(() => {
            fourInfoRef.value.updateFormData(modelForm)
            message.warning('请先完善必填数据')
          })
          return
        }
        submitData.fourInfo = modelForm
        state.data = { ...state.data, ...modelForm}
      }
      nextTick(() => {
        state.current = e
        switch (e) {
          case 0:
            (isEdit || !isEmpty(submitData.baseInfo)) && baseInfoFormRef.value.updateFormData(state.data)
          break;
          case 1: 
            (isEdit || !isEmpty(submitData.transferInfo)) && transferInfoFormRef.value.updateFormData(state.data)
          break;
          case 2:
            (isEdit || !isEmpty(submitData.otherInfo)) && otherInfoRef.value.updateFormData(state.data)
          break;
          case 3:
            (isEdit || !isEmpty(submitData.fourInfo)) && fourInfoRef.value.updateFormData(state.data)
          break;
        }
      })
    }
    const nextStep = async () => {
      const isEdit = !isEmpty(route.query.id)
      if (current.value === 0) {
        const { modelForm, errorFields } = await baseInfoFormRef.value.submit()
        if (errorFields) return
        submitData.baseInfo = modelForm
        state.data = { ...state.data, ...modelForm}
      }
      if (current.value === 1) {
        const { modelForm, errorFields } = await transferInfoFormRef.value.submit()
        if (errorFields) return
        submitData.transferInfo = modelForm
        state.data = { ...state.data, ...modelForm}
      }
      if (current.value === 2) {
        const { modelForm, errorFields } = await otherInfoRef.value.submit()
        if (errorFields) return
        submitData.otherInfo = modelForm
        state.data = { ...state.data, ...modelForm}
      }
      console.log('state.data: ', state.data);
      current.value++
      state.current = current.value
      if (isEdit) {
        await nextTick(() => {
          switch (current.value) {
            case 1:
              transferInfoFormRef.value.updateFormData(state.data)
              break;
            case 2:
              otherInfoRef.value.updateFormData(state.data)
              break;
            case 3:
              fourInfoRef.value.updateFormData(state.data)
              break;
          }
        })
      }
    }

    const saveForm = async () => {
      let result = true
      switch (current.value) {
        case 0: {
          const { modelForm, errorFields } = await baseInfoFormRef.value.submit()
          if (errorFields) result = false
          submitData.baseInfo = modelForm
          state.data = { ...state.data, ...modelForm}
        }
        break;
        case 1: {
          const { modelForm, errorFields } = await transferInfoFormRef.value.submit()
          if (errorFields) result = false
          submitData.transferInfo = modelForm
          state.data = { ...state.data, ...modelForm}
        }
        break;
        case 2: {
          const { modelForm, errorFields } = await otherInfoRef.value.submit()
          if (errorFields) result = false
          submitData.otherInfo = modelForm
          state.data = { ...state.data, ...modelForm}
        }
        break;
        case 3: {
          const { modelForm, errorFields } = await fourInfoRef.value.submit()
          if (errorFields) result = false
          submitData.fourInfo = modelForm
          state.data = { ...state.data, ...modelForm}
        }
        break;
      }
      if (!result) return
      let response, ajaxData = state.data
      ajaxData.schIntendedProject = Array.isArray(ajaxData.schIntendedProject)
                                  ? ajaxData.schIntendedProject.join(',')
                                  : ''
      ajaxData.schOnlineYesno = Array.isArray(ajaxData.schOnlineYesno)
                                  ? ajaxData.schOnlineYesno.join(',')
                                  : ''
      ajaxData.qualification = Array.isArray(ajaxData.qualification)
                                  ? ajaxData.qualification.join(',')
                                  : ''
      ajaxData.schProjectType = Array.isArray(ajaxData.schProjectType)
                                  ? ajaxData.schProjectType.join(',')
                                  : ''
      isEmpty(route.query.id)
        ? response = await save(ajaxData)
        : response = await update({ ...ajaxData, id: route.query.id })

      if (response.code == 500) return message.error(route.query.id ? response.msg : response.msg)
      if (response.code == 200) {
        message.success({
          content: route.query.id ? '修改成功' : '新增成功',
          onClose() {
            returnRoute()
          }
        })
      }
    }

    onMounted(async () => {
      console.log('onMounted: school add', );
      if (!isEmpty(route.query.id)) {
        const response = await selectById({ id: route.query.id })
        if (response.code === 500) return message.error('获取数据失败,请关闭tab重新打开')
        response.data.schIntendedProject = (typeof response.data.schIntendedProject) == 'string' && response.data.schIntendedProject
                                          ? response.data.schIntendedProject.split(',')
                                          : []
        response.data.schOnlineYesno = (typeof response.data.schOnlineYesno) == 'string' && response.data.schOnlineYesno
                                      ? response.data.schOnlineYesno.split(',')
                                      : []
        response.data.qualification = (typeof response.data.qualification) == 'string' && response.data.qualification
                                      ? response.data.qualification.split(',')
                                      : []
        response.data.schProjectType = (typeof response.data.schProjectType) == 'string' && response.data.schProjectType
                                      ? response.data.schProjectType.split(',')
                                      : []
        baseInfoFormRef.value.updateFormData(response.data)
        editData.data = response.data
        state.data = editData.data
      }
    })

    return {
      baseInfoFormRef,
      transferInfoFormRef,
      otherInfoRef,
      fourInfoRef,
      current,
      t,
      steps,
      submitData,
      nextStep,
      handleStep,
      saveForm
    }
  }

}
</script>
